package com.wxapp.common.base.redisson;

import com.wxapp.common.constant.properties.RedissonProperties;
import lombok.RequiredArgsConstructor;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;

/**
 * @author lgl
 * @Description
 * @Datetime 2023/7/12 15:02
 * @Modified By
 */
@Configuration
@RequiredArgsConstructor
public class RedissonConfig {
    private final RedissonProperties redissonProPerties;
    @Bean
    public RedissonClient redissonClient() {
        RedissonClient redissonClient;
        if (redissonProPerties.getEnv().equals("test")) {
            redissonClient = getRedissonCluster();
        } else {
            redissonClient = getRedissonSingle();
        }
        return redissonClient;
    }
    /**
     * 配置redisson集群
     */
    private RedissonClient getRedissonCluster() {
        List<String> clusterNodes = redissonProPerties.getNodeAddresses();
        Config config = new Config();
        //对象编码选择纯字符串编码
        config.setCodec(StringCodec.INSTANCE);
        ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));
        //设置密码
       clusterServersConfig.setPassword(redissonProPerties.getPassword());
        //redis连接心跳检测，防止一段时间过后，与redis的连接断开
        clusterServersConfig.setPingConnectionInterval(32000);
        return Redisson.create(config);
    }

    private RedissonClient getRedissonSingle() {
        Config config = new Config();
        config.setTransportMode(TransportMode.NIO);
        SingleServerConfig singleServerConfig = config.useSingleServer();
        //可以用"redis://"来启用SSL连接
        singleServerConfig.setAddress("redis://" + redissonProPerties.getHost() + ":" + redissonProPerties.getPort());
        singleServerConfig.setPassword(redissonProPerties.getPassword());
        RedissonClient redisson = Redisson.create(config);
        return redisson;
    }
}
